import os
from PIL import Image
import piexif
import threading,time
import shutil
from datetime import datetime

# pip install piexif Pillow

CONST_MAX_IMAGE = 4
CONST_MAX_VIDEO = 20

def ImageCompress(file_name):
    # path = file_name

    file_size = round(os.path.getsize(file_name)/(1024 * 1024),2)
    if file_size <= CONST_MAX_IMAGE:
        # print((datetime.now()).strftime('%Y-%m-%d %H:%M:%S'), file_name, '图片过小不使用压缩，', file_size, 'MB', '压缩阙值', CONST_MAX_IMAGE, 'MB')
        OtherCopy(file_name)
        return

    # print((datetime.now()).strftime('%Y-%m-%d %H:%M:%S'), file_name, '图片大小', file_size, 'MB')
    img = Image.open(file_name)
    exif = img.info.get('exif')
    destination = file_name.replace('input','output')
    os.makedirs(os.path.dirname(destination), exist_ok=True)
    background_color = (255, 255, 255)


    try:
        img.save(destination, "JPEG", quality=88, optimize=True, progressive=True, exif=exif) #转换就是直接另存为
    except IOError:
        PIL.ImageFile.MAXBLOCK = img.size[0] * img.size[1]
        img.save(destination, "JPEG", quality=88, optimize=True, progressive=True, exif=exif)

    file_size1 = round(os.path.getsize(destination)/(1024 * 1024),2)
    # print((datetime.now()).strftime('%Y-%m-%d %H:%M:%S'), destination, '转换完毕，图片大小', file_size1, 'MB')

def VideoCompress(file_name):

    file_size = round(os.path.getsize(file_name)/(1024 * 1024),2)
    if file_size <= CONST_MAX_VIDEO:
        # print((datetime.now()).strftime('%Y-%m-%d %H:%M:%S'), file_name, '视频过小不使用压缩，', file_size, 'MB', '压缩阙值', CONST_MAX_VIDEO, 'MB')
        OtherCopy(file_name)
        return
    
    # print((datetime.now()).strftime('%Y-%m-%d %H:%M:%S'), file_name, '视频大小', file_size, 'MB')
    # save_out_name = self.GetSaveOutFileName(file_name)
    destination = file_name.replace('input','output')
    os.makedirs(os.path.dirname(destination), exist_ok=True)

    command1 = r'.\\lib\\tools\\ffmpeg.exe -i "{}" -vn -sn -v 0 -c:a pcm_s16le -f wav pipe: | .\\lib\\tools\\neroAacEnc.exe -ignorelength -lc -br 128000 -if - -of ".\\lib\\old_atemp.mp4"'
    command2 = r'.\\lib\\tools\\x264_32-8bit.exe --crf 23.5 --preset 8 -I 600 -r 4 -b 3 --me umh -i 1 --scenecut 60 -f 1:1 --qcomp 0.5 --psy-rd 0.3:0 --aq-mode 2 --aq-strength 0.8 -o ".\\lib\\old_vtemp.mp4"  "{}"'
    command3 = r'.\\lib\\tools\\mp4box.exe -add ".\\lib\\old_vtemp.mp4#trackID=1:name=" -add ".\\lib\\old_atemp.mp4#trackID=1:name=" -new "{}"'
    command4 = "del .\\lib\\old_atemp.mp4 .\\lib\\old_vtemp.mp4"
    # command5 = r'del "{}"'

    os.system(command1.format(file_name))
    os.system(command2.format(file_name))
    os.system(command3.format(destination))
    os.system(command4)

    file_size1 = round(os.path.getsize(destination)/(1024 * 1024),2)
    # print((datetime.now()).strftime('%Y-%m-%d %H:%M:%S'), destination, '视频压缩完毕，视频大小', file_size1, 'MB')


def OtherCopy(file_name):

    # print((datetime.now()).strftime('%Y-%m-%d %H:%M:%S'), file_name, '拷贝文件')
    destination = file_name.replace('input','output')
    os.makedirs(os.path.dirname(destination), exist_ok=True)
    shutil.copy(file_name, destination)
    # print((datetime.now()).strftime('%Y-%m-%d %H:%M:%S'), destination, '拷贝完成')

def count_files_and_size(directory):
    file_count = 0
    total_size = 0
    for root, dirs, files in os.walk(directory):
        file_count += len(files)
        for file in files:
            file_path = os.path.join(root, file)
            total_size += os.path.getsize(file_path)
    return file_count, round(total_size/(1024*1024),2)


print("\r\n\r\n", (datetime.now()).strftime('%Y-%m-%d %H:%M:%S'), '正在启动压缩任务]')

output_path = os.getcwd()+'\\output'
if os.path.exists(output_path):
    shutil.rmtree(output_path)
    print((datetime.now()).strftime('%Y-%m-%d %H:%M:%S'), output_path , '清空output目录')

for d,_,fl in os.walk(os.getcwd()+'\\input'):    #遍历目录下所有文件
    for f in fl:
        try:
            file_name = d+'\\'+f
            
            # print((datetime.now()).strftime('%Y-%m-%d %H:%M:%S'), file_name, '开始处理')
            if file_name.split('.')[-1:][0] in ['png','jpg','jpeg','JPG']:
                ImageCompress(file_name)
            elif file_name.split('.')[-1:][0] in ['mp4','MP4','MOV']:
                VideoCompress(file_name)
            else:
                OtherCopy(file_name=file_name)

            # pass
        except:
            pass

file_count_org, total_size_org = count_files_and_size(os.getcwd()+'\\input')
file_count_trn, total_size_trn = count_files_and_size(os.getcwd()+'\\output') 

print((datetime.now()).strftime('%Y-%m-%d %H:%M:%S'), '压缩完成，原文件夹[',file_count_org,'个文件/',total_size_org,'mb]','新文件夹 [',file_count_trn,'个文件/',total_size_trn,'mb]')

# print(os.getcwd()+'\\input')